package cn.tmall.controller;

import cn.tmall.pojo.Category;
import cn.tmall.pojo.Property;
import cn.tmall.service.CategoryService;
import cn.tmall.service.PropertyService;
import cn.tmall.util.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.jws.WebParam;
import java.beans.PropertyEditor;
import java.util.List;

@Controller
@RequestMapping("")
public class PropertyController {
    @Resource(name = "PropertyServiceImpl")
    private PropertyService propertyService;
    @Resource(name = "CategoryServiceImpl")
    private CategoryService categoryService;

    @RequestMapping("admin_property_list")
    public String list(Model model, Page page, int cid) {
        Category category = categoryService.get(cid);

        PageHelper.offsetPage(page.getStart(), page.getCount());
        List<Property> propertyList = propertyService.list(cid);
        int total = (int) new PageInfo<>(propertyList).getTotal();
        page.setTotal(total);
        page.setParam("&cid=" + cid);

        model.addAttribute("category", category);
        model.addAttribute("page", page);
        model.addAttribute("propertyList", propertyList);
        return "admin/listProperty";
    }

    @RequestMapping("admin_property_add")
    public String add(Property property) {
        propertyService.add(property);
        return "redirect:admin_property_list?cid=" + property.getCid();
    }

    @RequestMapping("admin_property_delete")
    public String delete(int id) {
        int cid = propertyService.get(id).getCid();
        propertyService.delete(id);
        return "redirect:admin_property_list?cid=" + cid;
    }

    @RequestMapping("admin_property_edit")
    public String edit(Model model, int id) {
        Property property = propertyService.get(id);
        Category category = categoryService.get(property.getCid());
        property.setCategory(category);
        model.addAttribute("property", property);
        return "admin/editProperty";
    }

    @RequestMapping("admin_property_update")
    public String update(Property property) {
        propertyService.update(property);
        return "redirect:admin_property_list?cid=" + property.getCid();
    }
}
